package cn.javacart.jopencart.library;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

/**
 * Session级别Config服务
 * 主要包括，语言、币种等国际化配置
 * @author farmer
 *
 */
public class SessionConfigService {
	
	static final String CONFIG_MAP_KEY = "_config_map_key_";
	
	static ThreadLocal<HttpSession> threadLocal = new ThreadLocal<HttpSession>();
	
	/**
	 * 初始化
	 * @param session
	 */
	public static void init(HttpSession session){
		threadLocal.set(session);
	}
	
	@SuppressWarnings("unchecked")
	public static Map<String, Object> getConfigMap(){
		HttpSession httpSession = threadLocal.get();
		return (Map<String, Object>) httpSession.getAttribute(CONFIG_MAP_KEY);
	}
	
	/**
	 * 设置值
	 * @param key
	 * @param value
	 */
	public static void set(String key ,Object value){
		HttpSession httpSession = threadLocal.get();
		Map<String, Object> configMap = getConfigMap();
		if(configMap == null){
			configMap = new HashMap<String, Object>();
			httpSession.setAttribute(CONFIG_MAP_KEY, configMap);
		}
		configMap.put(key, value);
	}
	
	/**
	 * 获取设置的值
	 * @param key
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T get(String key){
		HttpSession httpSession = threadLocal.get();
		Map<String, Object> configMap = getConfigMap();
		if(configMap == null){
			configMap = new HashMap<String, Object>();
			httpSession.setAttribute(CONFIG_MAP_KEY, configMap);
		}
		return (T) configMap.get(key);
	}
	
	/**
	 * 重置
	 */
	public static void reset(){
		threadLocal.set(null);
	}
}
